package com.mh.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Date:2023/4/18
 * author:zmh
 * description: WebSocket消息处理类
 **/

@Component
@Slf4j
public class MyWebSocketHandler implements WebSocketHandler {

    // 维护所有连接会话的列表
    private static List<WebSocketSession> sessions = new ArrayList<>();

    /**
     * 群发消息（其他模块调用）
     * @param message 消息
     * @throws IOException ·
     */
    public static void senAll(String message){
        log.info("===========竞拍触发！");
        for (WebSocketSession s: sessions) {
            try {
                s.sendMessage(new TextMessage(message));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 将新连接的Session加入到集合中(确定连接之后触发此钩子)
        sessions.add(session);
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { // 消息处理，转发消息
        // 获取前端传入的消息
        String payload = (String) message.getPayload();

        // 拍卖触发处理，群发通知有人拍卖
        if("auction".equals(payload)){
            log.info("WS群发触发{}", payload);
            for (WebSocketSession s: sessions) {
                s.sendMessage(new TextMessage(payload));
            }
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        // 处理错误的连接，将连接删除
        this.sessions.remove(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        this.sessions.remove(session);
    }

    @Override
    public boolean supportsPartialMessages() {
        // 关闭部分消息的处理，等待所有消息到达后在做处理
        return false;
    }
}
